/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
/*
 * Topology Viewer
 */

package cgl.narada.topology.viewer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

//import com.ibm.ibmts.*;

/**
 * This class helps simulating the actual system where node addresses would 
 * come from some port.
 */
public class Simulation extends Thread {

    public static String tcp = "TCP";
    public static String udp = "UDP";
    public static String ssl = "SSL";
    
    public List nodeArray;
    public Random numberGenerator1;
    public Random numberGenerator2;
    public boolean addOrDelete;

    NodeManagement nodeManagement;
    Screen screen;

    int i;
    int parentSSClusterId;
    int id;
    int nodeCount;
    //ibmtslink ibmt;

    /**
     * Only constructor that makes use of common <code>NodeManagement</code>
     * and <code>Screen</code> objects (by <code>TopologyViewer</code>)
     */
    public Simulation(NodeManagement nm, Screen sc) {
	numberGenerator1 = new Random();
	numberGenerator2 = new Random();
	nodeArray = new ArrayList();
	nodeManagement = nm;
	screen = sc;
	i = 0;
	id = 0;
	nodeCount = 1;
    }

    /** 
     * Overrides run() of the <code>Thread</code> class.
     */
    public void run() {
	// sleep for 1 seconds
	try {
	    this.sleep(1000);
	} catch(InterruptedException ie) {
		System.out.println("Exception during thread sleep");
	}
	while(true) {
	    try {
		this.sleep(1000);
	    } catch(InterruptedException ie) {
		System.out.println("Exception during thread sleep");
	    }
	    if ((numberGenerator1.nextFloat() * 10) > 4) {
		manageNodes();
	    } else {
		manageLinks();
	    }
	    screen.display();
	}
    }

    /**
     * Depending upon the random number, either adds a node or deletes a node
     * in the system.
     */
    public void manageNodes() {
	if ((numberGenerator1.nextFloat() * 10) > 2) {
	    // for (int ct = 0; ct < 400; ct++) 
	    addNode();
	} else {
	    deleteNode();
	}
    }

    /**
     * Depending upon the random number, either adds a link or deletes a link
     * in the system.
     */
    public void manageLinks() {
	if ((numberGenerator1.nextFloat() * 10) > 2) {
	    // for (int ct = 0; ct < 50; ct++)
	    addLink();
	} else {
	    deleteLink();
	}
    }

    /**
     * Generates a random node address and invokes NodeManagement's method to
     * add the nodes. Also stores the node in local array required for 
     * simulation.
     */
    public void addNode() {
	int id4 = (int) (numberGenerator1.nextFloat() * 12);
	int id3 = (int) (numberGenerator1.nextFloat() * 12);
	int id2 = (int) (numberGenerator1.nextFloat() * 12);
	int id1 = (int) (numberGenerator1.nextFloat() * 12);
	String nodeAddress = String.valueOf(id4) + "." + 
	    String.valueOf(id3) + "." + 
	    String.valueOf(id2) + "." +
	    String.valueOf(id1);
	nodeManagement.addNode(nodeAddress);
	Node n = new Node(id1, id2, id3, id4);
	Iterator it = nodeArray.iterator();
	boolean found = false;
	while ((it.hasNext()) && (!found)) {
	    Node n1 = (Node) it.next();
	    if ((n1.nodeId == id1)
		&& (n1.parentClusterId == id2)
		&& (n1.parentSClusterId == id3)
		&& (n1.parentSSClusterId == id4)) {
		found = true;
	    }
	}
	if (!found) {
	    nodeArray.add(n);
	}

	// The Section below should be used only to measure plotting delyas or
	// zoom-in, zoom-out delays.
	
	/*
	if (nodeArray.size() > 200*nodeCount) {
	    screen.numNodes = nodeArray.size() - 1;
	    screen.display();
	    // First loop is to calculate plotting time delays.
	    // First and Second loop should be used together with proper count
	    // limits to calculate zoom-in and zoom-out response delays.
	    ibmt = new ibmtslink();
	    long epoch1, epoch2, diffMicro;
	    long readings[] = new long[51];
	    for (int count = 0; count < 51; count++) {
		epoch1 = ibmt.getEpochMicroseconds();
		screen.display();
		epoch2 = ibmt.getEpochMicroseconds();
		diffMicro = epoch2 - epoch1;
		readings[count] = diffMicro;
		//System.out.println("span = micro " + diffMicro);
	    }
	    for (int count = 25; count < 50; count++) {
		epoch1 = ibmt.getEpochMicroseconds();
		nodeManagement.zoomOut(396, 244);
		epoch2 = ibmt.getEpochMicroseconds();
		diffMicro = epoch2 - epoch1;
		readings[count] = diffMicro;
		//System.out.println("span = micro " + diffMicro);
	    }

	    // Following section prints the mean and deviation on stdout
	    System.out.println((nodeArray.size() - 1) + " " +
			       StatUtils.computeMean(readings, 51, 1));
	    System.out.println("DEVIATION = " +
	    		       StatUtils.computeStandardDeviation(readings,
								  30, 10));
	    System.out.println("\n");
	    nodeCount++;
	}
	*/
    }

    /**
     * From the stored local array of nodes, select one of the nodes for 
     * deletion and invokes NodeManagement's method.
     */
    public void deleteNode() {
	int length = nodeArray.size();
	if (length > 2) {
	    int index = numberGenerator2.nextInt(length);
	    if (index == 0) index++;
	    Node n = (Node) nodeArray.remove(index);
	    String nodeAddress = String.valueOf(n.parentSSClusterId) + "." + 
		String.valueOf(n.parentSClusterId) + "." + 
		String.valueOf(n.parentClusterId) + "." +
		String.valueOf(n.nodeId);
	    nodeManagement.deleteNode(nodeAddress);
	    screen.display();
	}
    }
    
    /**
     * Randomly selects nodes (some logic is applied so that nodes in same 
     * super-super cluster are selected, to show high clustering) and insert
     * a single link of one of the available types
     */
    public void addLink() {
	String n1 = getNode();
	String n2 = getNode();
	if ((n1 != null) && (n2 != null)) {
	    if (!n1.equals(n2)) {
		int type = (int) (numberGenerator1.nextFloat() * 3);
		String linkType;
		switch(type) {
		case 0: linkType = tcp;
		    break;
		case 1: linkType = udp;
		    break;
		default: linkType = ssl;
		    break;
		}
		try {
		    nodeManagement.addLink(n1, n2, id, linkType);
		} catch (TopologyException te) {
		    System.out.println("exception while adding a link");
		    System.out.println(te.explanation);
		}
	    }
	}
	id++;
    }

    /**
     * Deletes a existing link, for simplicity in this simulation all the 
     * existing links between pair are deleted. 
     */
    public void deleteLink() {
	// first select an existing link
	int length = nodeManagement.linkManagement.links.size();
	if (length > 1) {
	    int index = numberGenerator2.nextInt(length);
	    if (index == 0) index++;
	    LinkDetails link = (LinkDetails)
		nodeManagement.linkManagement.links.get(index);
	    nodeManagement.linkManagement.deleteLinksForPair(
							     link.connectedNode1, link.connectedNode2);
	}
    }
    
    /**
     * Gets a node address from existing node array.
     */
    public String getNode() {
	i++;
	int length = nodeArray.size();
	String nodeAddress = null;
	int index;
	Node n;
	// select other aribitrary
	if (length > 1) {
	    index = numberGenerator2.nextInt(length);
	    index = (index == 0) ? index++ : index;
	    n = (Node) nodeArray.get(index);
	    if (i == 2) { 
		// second call, try to get node in the same super super cluster
		if (numberGenerator1.nextFloat() * 10 > 1) {
		    // search for node in same super super cluster
		    index =  numberGenerator2.nextInt(length);
		    index = (index == 0) ? index++ : index;
		    n = (Node) nodeArray.get(index);
		    int numTry = 0;
		    while ((parentSSClusterId != n.parentSSClusterId) 
			   && (numTry < 50)) {
			index =  numberGenerator2.nextInt(length);
			n = (Node) nodeArray.get(index);
			numTry++;
		    }
		} 
	    }	    
	    if (i == 1) {
		parentSSClusterId = n.parentSSClusterId;
	    }
	    if (n == null) {
		index =  numberGenerator2.nextInt(length);
		n = (Node) nodeArray.get(index);
	    }
	    nodeAddress = String.valueOf(n.parentSSClusterId) + "." + 
		String.valueOf(n.parentSClusterId) + "." + 
		String.valueOf(n.parentClusterId) + "." +
		String.valueOf(n.nodeId);
	    i = i % 2;
	}
	return nodeAddress;
    }
};

    
